(function () {
	
	var codeIconWidth=50;
	 var codeIconHeight=50;
	function downloadImage(src,name) {
	    var $a = $("<a></a>").attr("href", src).attr("download", name+".png");
	    $a[0].click();
	}
	
	function doQuery(){
        serverData.key=jQuery("#search").val();
        serverData.level=jQuery("#bussinessLevelId").val();
        serverTable.draw();
	}
	
    //查询
    jQuery('.app-btn-search').on('click',function(){
    	doQuery();
    });
    //撤销查询
    jQuery('.app-btn-cancel').on('click',function(){
        jQuery('#search').val('');
        serverData.key='';
        serverTable.draw();
    });
    
    ///下载图片
    jQuery('.downloadBtn').on('click', function () {
    	downloadImage($("#dimg").attr("src"),jQuery('#shopName').val());
    });
    
    ///批量下载图片
    jQuery('.downloadBtnP').on('click', function () {
    	$(".downloadBtnE").trigger("click");
    });

    
////////////////初始化模型的树结构/////////////////////////
    var modalSetting = {
        edit:{
            enable: true,
            showRemoveBtn:false,
            showRenameBtn:false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootParentId: 0,
            }
        },
        view:{
            showLine:true
        },
        check: {
			enable: false,
			chkStyle: "radio",
			radioType: "all"
		},
        callback:{
        	onClick:editNewModule
        }

    };
    
    //菜单树点击编辑节点
    function editNewModule(e, treeId, treeNode){
    	var bussinessLevelId=treeNode.id;
    	/*
    	if(treeNode.checked){
    		jQuery('#bussinessLevelId').val(bussinessLevelId);
    	}else{
    		//未选中将清空数据
    		jQuery('#bussinessLevelId').val('');
    	}
    	*/
    	if(bussinessLevelId != '0'){
    		jQuery('#bussinessLevelId').val(bussinessLevelId);
    	}else{
    		//未选中将清空数据
    		jQuery('#bussinessLevelId').val('');
    	}
    	doQuery();
    }
    
    
    var primaryNode=[];
    var url = window.rootPath +'/ui/businessshow/getBussinessLevelAllNodes';
    jQuery.ajax({
        url:url,
        cache:false,
        type :"get",
        dataType:"json",
        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
        success:function(data){
                primaryNode.push(
                    {
                        id: 0,
                        name: "商户区域",
                        open: "true",
                    	nocheck: "true",
                    	icon: "/wcsi/img/defaultDivision.png"
                        // iconSkin:"diy03"
                    }
                );
                for (var i = 0; i < data.nodes.length; i++) {
                    primaryNode.push(data.nodes[i]);
                }
            $.fn.zTree.init($("#bussinessLevelTree"),modalSetting,primaryNode);
        }
    });
    
    
    var serverData = {};
    var serverTable;
    jQuery(document).ready(function () {
        serverTable = jQuery('#dataTable').DataTable({
            "iDisplayLength" : 100,
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/businessshow/getbaseinfopage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                data: null
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {
                        var operate ='<button type="button" class="btn btn-sm btn-info searchBtn" title="查看详情"><i class="fa fa-search"></i></button>'
                        	+'<button type="button" class="btn btn-sm btn-info downloadBtnE" title="下载二维码"><i class="fa fa-download"></i></button>';
                        return operate;

                    }
                },
                {
                    //data: 'infoState.title'
                	data: null,
            	    render : function(data,type, full,meta) {
						var dOut;
						if(data.infoState!=undefined){
						/*if (data.infoState.title == '待认证') {
							dOut = '<td class="center" ><span class="badge label-pill label-primary">待认证</span></td>';
						} else if (data.infoState.title == '认证拒绝') {
							dOut = '<td class="center" ><span class="badge label-pill label-danger">认证拒绝</span></td>';
						} else if (data.infoState.title == '认证通过') {
							dOut = '<td class="center" ><span class="badge label-pill label-success">认证通过</span></td>';
						} else if (data.infoState.title == '初始化') {
							dOut = '<td class="center" ><span class="badge label-pill label-default">初始化</span></td>';
						} else if(data.infoState.title	==null){
							dOut='';
						}*/
							if (data.infoState.title == '待认证') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_in.png"/></td>';
							} else if (data.infoState.title == '认证拒绝') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_notaccess.png"/></td>';
							} else if (data.infoState.title == '认证通过') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_access.png"/></td>';
							} else if (data.infoState.title == '初始化') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_init.png"/></td>';
							} else if(data.infoState.title	==null){
								dOut='';
							}
						}
						return dOut;
					}
                },
                {
                    data: 'shopName',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'shopAdress',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'bussinessLevel.levelName',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                /*{
                    data: 'areaInfo.value',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },*/
                {
                    data: 'bussinessLevel.userName',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                /*{
                    data: 'areaMeasure',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },*/
                {
                    data: 'signPerson'
                },
                {
                    data: 'managementRange',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'managementPerson.name'
                },
               /* {
                    data: 'memo'
                },*/
                {
                	data: null,
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							
							var codeUrl =window.rootPath+data.codeAdress;
							 codeUrl=window.location.origin+codeUrl;
							//codeUrl="http://www.exde.com.cn:9999"+codeUrl;
							
							 /*codeUrl=encodeURIComponent(codeUrl);
							 codeUrl="https://open.weixin.qq.com/connect/qrconnect?appid=wx68f7e13d025bc3ad&redirect_uri="+codeUrl
							 +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";*/
							 
							 $('#qrcode').html("");
							
							/*var qrcode= jQuery('#qrcode').qrcode(codeUrl).hide();*/   
							 var qrcode =jQuery('#qrcode').qrcode({
								    render: "canvas", //也可以替换为table
								    width: 300,
								    height: 300,
								    text:codeUrl
								}).hide();
							 
							 var canvas=qrcode.find('canvas').get(0);
							 
							 var ctx=canvas.getContext('2d');
							 var myImage=document.getElementById("qrCodeIco");
							 ctx.drawImage(myImage, canvas.width/2-codeIconWidth/2, canvas.height/2-codeIconHeight/2, codeIconWidth, codeIconHeight);
							 ctx.moveTo(canvas.width/2-codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第一个起点
				              ctx.lineTo(canvas.width/2+codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第二个点
				              ctx.lineTo(canvas.width/2+codeIconWidth/2,canvas.height/2+codeIconHeight/2);//第三个点（以第二个点为起点）
				              ctx.lineTo(canvas.width/2-codeIconWidth/2,canvas.height/2+codeIconHeight/2);//第四个点（以第二个点为起点）
				              ctx.lineTo(canvas.width/2-codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第五个点（以第二个点为起点）
				              ctx.lineWidth = 5;
				              ctx.strokeStyle = '#ffffff';
				              ctx.stroke();
				              
							 /*<div id="qrcodeM" width="30%"></div>
							   <img id="imageM" src=""/>
							   var imageM = $("#imageM");
							 imageM.src = canvas.toDataURL("imageM/png"); */
							
							 //var img =canvas.toDataURL('image/jpg');
							return '<img width="100%" src="'+canvas.toDataURL("image/png")+'" />';
						}
					}
                }
              ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }

                serverTable.off('click', 'tr');
                serverTable.on('click', 'tr', function (event) {
                    event = event || window.event;
                    var target = event.target || event.scrElement;
                    var data = serverTable.row(this).data();
                    if (target.className.indexOf('fa-download') != -1 || target.className.indexOf('downloadBtnE') != -1) {
                    	downloadQ(data);
                    }
                    
                    if (target.className.indexOf('fa-search') != -1 || target.className.indexOf('searchBtn') != -1) {
                        showDetail(data);
                    }

                    return;
                });
            }
        });
        
        var downloadQ=function(data){
        	
        	var codeUrl =window.rootPath+data.codeAdress;
			 codeUrl=window.location.origin+codeUrl;
			 
			 $('#qrcode').html("");
			 var qrcode =jQuery('#qrcode').qrcode({
				    render: "canvas", //也可以替换为table
				    width: 300,
				    height: 300,
				    text:codeUrl
				}).hide();
			 var canvas=qrcode.find('canvas').get(0);
			 
			 var ctx=canvas.getContext('2d');
			 var myImage=document.getElementById("qrCodeIco");
			 ctx.drawImage(myImage, canvas.width/2-codeIconWidth/2, canvas.height/2-codeIconHeight/2, codeIconWidth, codeIconHeight);
			 ctx.moveTo(canvas.width/2-codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第一个起点
              ctx.lineTo(canvas.width/2+codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第二个点
              ctx.lineTo(canvas.width/2+codeIconWidth/2,canvas.height/2+codeIconHeight/2);//第三个点（以第二个点为起点）
              ctx.lineTo(canvas.width/2-codeIconWidth/2,canvas.height/2+codeIconHeight/2);//第四个点（以第二个点为起点）
              ctx.lineTo(canvas.width/2-codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第五个点（以第二个点为起点）
              ctx.lineWidth = 5;
              ctx.strokeStyle = '#ffffff';
              ctx.stroke();
			 
			 
			 downloadImage(canvas.toDataURL("image/png"),data.shopName);
        };
        $("#avatar").error(function() { 
        	$(this).attr("src", "../img/empty.png"); 
        	$(this).error=null;
        	});
        var showDetail=function(data){
        	if(!data) return;
        	
        	/*var avatarUrl=window.rootPath+'/a/'+'avatar/'+data.pictureAdress;
        	

        		jQuery("#avatar").prop("src",avatarUrl+'?t='+Math.random());*/
        	var purl=data.pictureAdress;
			if(purl==undefined||purl==""){
				purl="../img/nopicture.png";
			}else{
				purl=window.rootPath+'/'+purl;
			}
			$("#avatar").attr("src",purl);
        	
    		if(data.infoState!=undefined){
    			var path ="";
        		if (data.infoState.title == '待认证') {
        			path="../img/authentication_in.png";
				} else if (data.infoState.title == '认证拒绝') {
					path="../img/authentication_notaccess.png";
				} else if (data.infoState.title == '认证通过') {
					path="../img/authentication_access.png";
				} else if (data.infoState.title == '初始化') {
					path="../img/authentication_init.png";
				} else if(data.infoState.title	==null){
					path ="";
				}
        		$("#infoState").attr('src',path); 
    			/*jQuery('#infoState').val(data.infoState.title);	*/
    		}
    		
        	jQuery('#id').val(data.id);
        	jQuery('#createTime').val(data.createTime)
        	jQuery('#latitude').val(data.latitude)
        	jQuery('#longitude').val(data.longitude)
    		jQuery('#checkDate').val(data.checkDate);
        	jQuery('#submitDate').val(data.submitDate);
    		jQuery('#shopName').val(data.shopName);	
    		jQuery('#shopAdress').val(data.shopAdress);
    		
    		if(data.bussinessLevel!=undefined){
        		jQuery('#areaInfo').val(data.bussinessLevel.levelName);
        		jQuery('#areaInfoPhone').val(data.bussinessLevel.phoneNumber);	
        		if(data.bussinessLevel.userName!=undefined){
        			jQuery('#arreaManagementPerson').val(data.bussinessLevel.userName);
        		}
    		}
    		jQuery('#areaMeasure').val(data.areaMeasure);
    		jQuery('#signPerson').val(data.signPerson);
    		jQuery('#managementRange').val(data.managementRange);
    		jQuery('#cleaningPerson').val(data.cleaningPerson);
    		if(data.managementPerson){
    			jQuery('#managementPerson').val(data.managementPerson.name);	
    		}
			jQuery('#memo').val(data.memo);
			var codeUrl =window.rootPath+data.codeAdress;
			 codeUrl=window.location.origin+codeUrl;
			 
			 $('#qrcode').html("");
			/*jQuery('#qrcode').qrcode(codeUrl);*/
			
			var qrcode =jQuery('#qrcode').qrcode({
			    render: "canvas", //也可以替换为table
			    width: 300,
			    height: 300,
			    text:codeUrl
			}).hide();
		 var canvas=qrcode.find('canvas').get(0);
		 
		 var ctx=canvas.getContext('2d');
		 var myImage=document.getElementById("qrCodeIco");
		 ctx.drawImage(myImage, canvas.width/2-codeIconWidth/2, canvas.height/2-codeIconHeight/2, codeIconWidth, codeIconHeight);
		 ctx.moveTo(canvas.width/2-codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第一个起点
          ctx.lineTo(canvas.width/2+codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第二个点
          ctx.lineTo(canvas.width/2+codeIconWidth/2,canvas.height/2+codeIconHeight/2);//第三个点（以第二个点为起点）
          ctx.lineTo(canvas.width/2-codeIconWidth/2,canvas.height/2+codeIconHeight/2);//第四个点（以第二个点为起点）
          ctx.lineTo(canvas.width/2-codeIconWidth/2,canvas.height/2-codeIconHeight/2);//第五个点（以第二个点为起点）
          ctx.lineWidth = 5;
          ctx.strokeStyle = '#ffffff';
          ctx.stroke();
          
		 $('#dimg').attr('src',canvas.toDataURL('dimg/png'));
			/*//使用table生成
			jQuery('#qrcode').qrcode({
			    render: "table",
			    text: "http://www.jq22.com"
			});
			 
			//使用canvas生成
			jQuery('#qrcode').qrcode({
			    render: "canvas",
			    text: "http://www.jq22.com"
			});*/
			
			/*//生成100*100(宽度100，高度100)的二维码
			jQuery('#qrcode').qrcode({
			    render: "canvas", //也可以替换为table
			    width: 100,
			    height: 100,
			    text: "http://www.jq22.com"
			});*/
			/*//生成前景色为红色背景色为白色的二维码
			jQuery('#qrcode').qrcode({
			    render: "canvas", //也可以替换为table
			    foreground: "#C00",
			    background: "#FFF",
			    text: "http://www.jq22.com"
			});*/
			
			/*if(data.checkPerson){
				jQuery('#checkPerson').val(data.checkPerson.name);	
			}*/
    		jQuery('#checkModal').modal('show');
        }
    });
    
    function download(canvasElem, filename, imageType) {
        var event, saveLink, imageData, defalutImageType;
        defalutImageType = 'png';//定义默认图片类型
        imageData = canvasElem.toDataURL(imageType || defalutImageType);//将canvas元素转化为image data
        saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
        saveLink.href = imageData;
        saveLink.download = filename;
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        saveLink.dispatchEvent(event);
    };
    
    
    
    
})();